#include <Windows.h>
#include <tchar.h>
#include "resource.h"

int CALLBACK DlgProc(HWND hDlg, UINT nMsg, WPARAM wParam, LPARAM lParam)
{
	static bool bBtnDown = false;
	static COLORREF crColor;
	switch (nMsg)
	{
		case WM_INITDIALOG:
		{
			SetWindowText(hDlg, _T("Demo0100"));

			UINT nWidth		= GetSystemMetrics(SM_CXSCREEN);
			UINT nHeight	= GetSystemMetrics(SM_CYSCREEN);
			RECT rtClient;
			GetClientRect(hDlg, &rtClient);
			SetWindowPos(hDlg, NULL, (nWidth - (rtClient.right - rtClient.left)) / 2, (nHeight - (rtClient.bottom - rtClient.top)) / 2, 0, 0, SWP_NOSIZE);
			
			break;
		}
		case WM_LBUTTONDOWN:
		{
			bBtnDown = true;
			SetCapture(hDlg);
			
			break;
		}
		case WM_MOUSEMOVE:
		{
			if (bBtnDown)
			{
				POINT pos;
				GetCursorPos(&pos);
				TCHAR szTmp[MAX_PATH];
				_stprintf(szTmp, _T("x: %d, y: %d"), pos.x, pos.y);
				SetDlgItemText(hDlg, IDC_STCPOS, szTmp);
				
				HDC hDC = CreateDC(_T("Display"), NULL, NULL, NULL);
				crColor = GetPixel(hDC, pos.x, pos.y);
				_stprintf(szTmp, _T("RGB(%d, %d, %d)"), GetRValue(crColor), GetGValue(crColor), GetBValue(crColor));
				SetDlgItemText(hDlg, IDC_STCCOLOR, szTmp);
				DeleteDC(hDC);
				InvalidateRect(hDlg, NULL, FALSE);
			}
			
			break;
		}
		case WM_PAINT:
		{
			PAINTSTRUCT ps;
			HDC hDC = BeginPaint(hDlg, &ps);
			if (bBtnDown)
			{
				RECT rtCtrl;
				GetClientRect(GetDlgItem(hDlg, IDC_STCVIEW), &rtCtrl);
				InflateRect(&rtCtrl, -5, -5);
				
				MapWindowPoints(GetDlgItem(hDlg, IDC_STCVIEW), hDlg, (LPPOINT)&rtCtrl, 2);

				HBRUSH hBrush = CreateSolidBrush(crColor);
				FillRect(hDC, &rtCtrl, hBrush);
				DeleteObject(hBrush);
			}
			EndPaint(hDlg, &ps);
			break;
		}
		case WM_LBUTTONUP:
		{
			bBtnDown = false;
			ReleaseCapture();
			break;
		}
		case WM_CLOSE:
		{
			PostQuitMessage(0);
			break;
		}
	}

	return 0;
}

BOOL WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPreInstance, LPTSTR szCmdLine, int nShowCmd)
{
	DialogBox(hInstance, MAKEINTRESOURCE(IDD_DIALOG), NULL, DlgProc);

	return TRUE;
}